<template>
    <view class="container">
      <view class="title">申请状态</view>
      
      <view v-if="!hasEnrollment" class="empty-tip card">
        <text>您还没有报名记录</text>
        <button class="btn-primary" size="mini" @click="navigateTo('/pages/enrollment/apply/apply')">立即报名</button>
      </view>
      
      <block v-else>
        <view class="status-container card">
          <view class="status-header">
            <view class="status-title">报名状态</view>
            <view class="status-badge" :class="getStatusClass(currentEnrollment.status)">
              {{ getStatusText(currentEnrollment.status) }}
            </view>
          </view>
          
          <view class="status-timeline">
            <view 
              class="timeline-item" 
              :class="{ active: isStepActive('applying') }"
              v-if="currentEnrollment"
            >
              <view class="timeline-dot"></view>
              <view class="timeline-content">
                <view class="timeline-title">提交申请</view>
                <view class="timeline-desc">
                  {{ formatDate(currentEnrollment.created_at) }}
                </view>
              </view>
            </view>
            
            <view 
              class="timeline-item" 
              :class="{ active: isStepActive('material') }"
              v-if="currentEnrollment && currentEnrollment.status !== 'pending'"
            >
              <view class="timeline-dot"></view>
              <view class="timeline-content">
                <view class="timeline-title">材料审核</view>
                <view class="timeline-desc">
                  {{ getTimelineDesc('material') }}
                </view>
              </view>
            </view>
            
            <view 
              class="timeline-item" 
              :class="{ active: isStepActive('approved') }"
              v-if="currentEnrollment && currentEnrollment.status === 'approved'"
            >
              <view class="timeline-dot"></view>
              <view class="timeline-content">
                <view class="timeline-title">申请通过</view>
                <view class="timeline-desc">
                  恭喜您，报名申请已通过审核
                </view>
              </view>
            </view>
            
            <view 
              class="timeline-item" 
              :class="{ active: isStepActive('rejected') }"
              v-if="currentEnrollment && currentEnrollment.status === 'rejected'"
            >
              <view class="timeline-dot"></view>
              <view class="timeline-content">
                <view class="timeline-title">申请拒绝</view>
                <view class="timeline-desc">
                  很抱歉，您的申请未通过审核：{{ currentEnrollment.remark || '无原因说明' }}
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <view class="enrollment-detail card">
          <view class="detail-title">报名详情</view>
          
          <view class="detail-list">
            <view class="detail-item">
              <text class="detail-label">姓名：</text>
              <text class="detail-value">{{ currentEnrollment.user ? currentEnrollment.user.real_name : '' }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">驾照类型：</text>
              <text class="detail-value">{{ getLicenseTypeText(currentEnrollment.license_type) }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">报名时间：</text>
              <text class="detail-value">{{ formatDate(currentEnrollment.created_at, 'YYYY-MM-DD HH:mm') }}</text>
            </view>
            <view class="detail-item" v-if="currentEnrollment.coach">
              <text class="detail-label">教练：</text>
              <text class="detail-value">{{ currentEnrollment.coach.real_name }}</text>
            </view>
          </view>
        </view>
        
        <view class="document-container card" v-if="currentEnrollment.status === 'approved'">
          <view class="document-title">相关文件</view>
          
          <view class="document-list">
            <view class="document-item" @click="generateForm('enrollment')">
              <text class="document-icon">📄</text>
              <text class="document-name">报名表</text>
              <text class="document-status" v-if="currentEnrollment.form_generated">已生成</text>
            </view>
            <view class="document-item" @click="generateForm('medical')">
              <text class="document-icon">🏥</text>
              <text class="document-name">体检表</text>
              <text class="document-status" v-if="currentEnrollment.medical_form_generated">已生成</text>
            </view>
          </view>
        </view>
        
        <view class="action-container">
          <button 
            class="btn-primary" 
            v-if="currentEnrollment.status === 'pending'" 
            @click="navigateTo(`/pages/enrollment/materials/materials?id=${currentEnrollment.id}`)"
          >
            上传材料
          </button>
          
          <button 
            class="btn-primary" 
            v-if="currentEnrollment.status === 'approved' && !currentEnrollment.coach_id" 
            @click="navigateTo('/pages/enrollment/coach-selection/coach-selection')"
          >
            选择教练
          </button>
          
          <button 
            class="btn-default" 
            style="margin-top: 20rpx;" 
            @click="navigateBack"
          >
            返回
          </button>
        </view>
      </block>
    </view>
  </template>
  
  <script>
  import { mapActions, mapGetters } from 'vuex';
  import { formatDate } from '@/utils/date';
  import config from '@/config/index';
  
  export default {
    data() {
      return {
        enrollmentId: ''
      };
    },
    computed: {
      ...mapGetters('enrollment', [
        'myEnrollments',
        'currentEnrollment',
        'hasEnrollment'
      ])
    },
    onLoad(options) {
      if (options.id) {
        this.enrollmentId = options.id;
        this.getEnrollment(this.enrollmentId);
      } else {
        // 获取最新报名记录
        this.getMyEnrollments();
      }
    },
    methods: {
      ...mapActions('enrollment', [
        'getMyEnrollments',
        'getEnrollment',
        'generateEnrollmentForm',
        'generateMedicalForm'
      ]),
      formatDate,
      navigateTo(url) {
        uni.navigateTo({
          url
        });
      },
      navigateBack() {
        uni.navigateBack();
      },
      getStatusText(status) {
        const statusMap = {
          'pending': '待提交材料',
          'reviewing': '审核中',
          'approved': '已通过',
          'rejected': '已拒绝'
        };
        return statusMap[status] || status;
      },
      getStatusClass(status) {
        const classMap = {
          'pending': 'status-pending',
          'reviewing': 'status-reviewing',
          'approved': 'status-approved',
          'rejected': 'status-rejected'
        };
        return classMap[status] || '';
      },
      getLicenseTypeText(type) {
        const license = config.licenseTypes.find(item => item.value === type);
        return license ? license.label : type;
      },
      isStepActive(step) {
        if (!this.currentEnrollment) return false;
        
        switch (step) {
          case 'applying':
            return true;
          case 'material':
            return ['reviewing', 'approved', 'rejected'].includes(this.currentEnrollment.status);
          case 'approved':
            return this.currentEnrollment.status === 'approved';
          case 'rejected':
            return this.currentEnrollment.status === 'rejected';
          default:
            return false;
        }
      },
      getTimelineDesc(step) {
        if (!this.currentEnrollment) return '';
        
        switch (step) {
          case 'material':
            if (this.currentEnrollment.status === 'reviewing') {
              return '材料正在审核中，请耐心等待';
            } else if (this.currentEnrollment.status === 'approved') {
              return '材料审核通过';
            } else if (this.currentEnrollment.status === 'rejected') {
              return '材料审核未通过';
            }
            return '';
          default:
            return '';
        }
      },
      generateForm(type) {
        if (!this.currentEnrollment || this.currentEnrollment.status !== 'approved') {
          this.showToast('报名未通过，无法生成表格');
          return;
        }
        
        uni.showLoading({
          title: '生成中...'
        });
        
        if (type === 'enrollment') {
          // 生成报名表
          this.generateEnrollmentForm(this.currentEnrollment.id)
            .then(res => {
              uni.hideLoading();
              // 预览或下载PDF
              uni.downloadFile({
                url: res.data.url,
                success: function(res) {
                  const filePath = res.tempFilePath;
                  uni.openDocument({
                    filePath: filePath,
                    showMenu: true,
                    success: function() {
                      console.log('打开文档成功');
                    }
                  });
                }
              });
            })
            .catch(err => {
              uni.hideLoading();
              this.showToast(err.message || '生成报名表失败');
            });
        } else if (type === 'medical') {
          // 生成体检表
          this.generateMedicalForm(this.currentEnrollment.id)
            .then(res => {
              uni.hideLoading();
              // 预览或下载PDF
              uni.downloadFile({
                url: res.data.url,
                success: function(res) {
                  const filePath = res.tempFilePath;
                  uni.openDocument({
                    filePath: filePath,
                    showMenu: true,
                    success: function() {
                      console.log('打开文档成功');
                    }
                  });
                }
              });
            })
            .catch(err => {
              uni.hideLoading();
              this.showToast(err.message || '生成体检表失败');
            });
        }
      }
    }
  };
  </script>
  
  <style lang="scss">
  .container {
    padding: 30rpx;
  }
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 40rpx;
  }
  
  .empty-tip {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    margin-bottom: 30rpx;
  }
  
  .status-container, .enrollment-detail, .document-container {
    margin-bottom: 30rpx;
    padding: 30rpx;
  }
  
  .status-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
  }
  
  .status-title {
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .status-badge {
    font-size: 24rpx;
    padding: 4rpx 16rpx;
    border-radius: 20rpx;
  }
  
  .status-pending {
    background-color: #fff7e6;
    color: #e6a23c;
  }
  
  .status-reviewing {
    background-color: #e6f7ff;
    color: #1890ff;
  }
  
  .status-approved {
    background-color: #e6f7f0;
    color: #52c41a;
  }
  
  .status-rejected {
    background-color: #fff3f3;
    color: #f56c6c;
  }
  
  .status-timeline {
    position: relative;
    padding-left: 30rpx;
  }
  
  .status-timeline:before {
    content: '';
    position: absolute;
    left: 10rpx;
    top: 0;
    bottom: 0;
    width: 2rpx;
    background-color: #eee;
  }
  
  .timeline-item {
    position: relative;
    padding-bottom: 40rpx;
  }
  
  .timeline-item:last-child {
    padding-bottom: 0;
  }
  
  .timeline-dot {
    position: absolute;
    left: -30rpx;
    top: 10rpx;
    width: 20rpx;
    height: 20rpx;
    border-radius: 50%;
    background-color: #ddd;
    z-index: 1;
  }
  
  .timeline-item.active .timeline-dot {
    background-color: #3c8dbc;
  }
  
  .timeline-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }
  
  .timeline-desc {
    font-size: 26rpx;
    color: #666;
  }
  
  .timeline-item.active .timeline-title {
    color: #3c8dbc;
  }
  
  .detail-title, .document-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
  }
  
  .detail-list {
    margin-bottom: 20rpx;
  }
  
  .detail-item {
    display: flex;
    margin-bottom: 20rpx;
  }
  
  .detail-label {
    width: 160rpx;
    font-size: 28rpx;
    color: #666;
  }
  
  .detail-value {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
  
  .document-list {
    display: flex;
    flex-wrap: wrap;
  }
  
  .document-item {
    width: 32%;
    margin-right: 2%;
    margin-bottom: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20rpx 0;
    border: 1px solid #eee;
    border-radius: 6rpx;
  }
  
  .document-item:nth-child(3n) {
    margin-right: 0;
  }
  
  .document-icon {
    font-size: 50rpx;
    margin-bottom: 10rpx;
  }
  
  .document-name {
    font-size: 26rpx;
    margin-bottom: 10rpx;
  }
  
  .document-status {
    font-size: 22rpx;
    color: #52c41a;
  }
  
  .action-container {
    margin-top: 40rpx;
  }
  
  .btn-primary, .btn-default {
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    font-size: 32rpx;
    border-radius: 8rpx;
  }
  
  .btn-primary {
    color: #fff;
    background-color: #3c8dbc;
  }
  
  .btn-default {
    color: #666;
    background-color: #f8f8f8;
    border: 1px solid #ddd;
  }
  </style>